require("./header/header")
let dia = require("./dialog")
let paojiaoyun = require("./paojiaoyun")


let dialib = new dia()

module.exports = function () {
    this.g_name = "bh"
    this.g_version = "beta X"
    this.g_workpath = files.cwd()

    this.__ids__ = []

    this.pjyconfig = {
        appkey: "c0bosdso6itd9d2u21h0",
        secret: "LjdrmQy1VRTUp86Ubmr2RUslAHji9I2s"
    }
    
    this.pjysdk = new paojiaoyun(this.pjyconfig.appkey, this.pjyconfig.secret)    
    this.isroot = false
    this.pjysdk.event.on("heartbeat_failed", function () {
        console.log(hret.message)
        if (hret.code === 10214) {
            sleep(200);
            exit();  // 退出脚本
        }
        console.log("心跳失败，尝试重登...")
        sleep(2000);
        let login_ret = this.pjysdk.CardLogin()
        
        // this.store.put("pjysdk_login_ret", login_ret)

        if (login_ret.code === 0) {
            log("重登成功");
            this.isroot = true
            
            // this.mutations.pjysdk_updata(login_ret.result)
        } else {
            toastLog(login_ret.message);  // 重登失败
            sleep(200);
            exit();  // 退出脚本

        }
        
    })

    // 悬浮窗
    this.b_floaty = false
    this.b_access = true
    this.b_battery = true
    
    this.b_run = false
    this.b_init = false

    this.store = null

    this.__debug__ = true

    this.__uiConfig__ = {
        tabs : [],
        color: "#FFC0CB",
        title: "Title",
        subTitile: "",
        version: "0.0.0",
        package: "v.chaod.chen",
        tabs_color: "#ffffff"
    }

    // 回调函数组
    this.checkfun = []
    
    this._testObject = function (obj, ks) {
        if (!obj || !ks) return -1;
        if (!(obj instanceof Object)) return -1;
        if (!(ks instanceof Array)) return -1;

        for (let i = 0;i < ks.length; i++) {
            if (!(ks[i] in obj)) return -1;
        }
        return 0
    }
    
    this.init = function (p) {
        http.__okhttp__.setMaxRetries(0)
        http.__okhttp__.setTimeout(10*1000)
        if (!p) return -1;
        if (!(p instanceof Object)) return -1;
        if (this._testObject(p, ["name", "versionName", "packageName"]) != 0) return -1;

        this.__uiConfig__.title = p.name
        this.__uiConfig__.version = p.versionName
        this.__uiConfig__.package = p.packageName
        // 创建班花模板本地存储
        this.store = storages.create(p.packageName)

        this.templace = Jsoup.parse(this.__templace__)
        this.__uiInit__()
        this.b_init = true

        return 0
    }

    this.addgroup = function(qun) {
        try {
            app.startActivity({
                action: "android.intent.action.VIEW",
                data:   "mqqapi://card/show_pslcard?src_type=internal&version=1&uin=" 
                        + qun + "&card_type=group&source=qrcode"
            });
        } catch (e) {
            toast("加入 " + qun + " QQ群失败,手动加吧");
        }
    }

    this.setTabs = function (tabarr) {
        if (!tabarr)  return -1;
        if (!(tabarr instanceof Array)) return -1;
        this.__uiConfig__.tabs = tabarr
        return 0
    }

    this.setColor = function (cstr) {
        if (!cstr) return -1;
        if (!(cstr instanceof String)) return -1;
        this.__uiConfig__.color = cstr
        return 0
    }

    this.__templace__ = (
        <vertical w='*' h="*" id="__main__">
            <appbar id="appbar">
            </appbar>
        </vertical>
    )

    // this.addCard = function (xml, tab) {
    //     let temp = <card cardCornerRadius="15dp" cardElevation="3dp" w="*" h="*" margin="6dp">
    //         <vertical>
    //             {xml}
    //         </vertical>
    //     </card>
    //     return this.addView(temp, tab)
    // }

    this.addView = function (xml, tab, fun) {
        if (!xml) return -1;
        if (!this.b_init) throw "未初始化";
        if (!tab) {
            this.__uiConfig__.tabs.length > 0 ? tab = this.__uiConfig__.tabs[0] : tab = "main";
        }

        if (!this.b_run) {
            let body = this.templace.getElementById(tab)
            body.append(xml)
            delete body
        } else {
            tab = ui[tab]
            if (!tab) return -1;

            // 采集id
            let res = xml.toString().match(/bh_\w+/g)
            print("res-->> ")
            
            print(res)
            if (res != null) {
                this.__ids__ = this.__ids__.concat(res)

            }
            log("开始绘制")
            ui.inflate(xml, tab, true)
            if (fun != null && fun instanceof Function) {
                fun.call(this)
            }
            delete tab
        }
        
        // 添加回调函数
        if (fun !=null && fun instanceof Function) this.checkfun.push(fun);
        return 0
    }

    this.user_center = function () {
        ui.layout(
            <vertical>
                <appbar id="appbar">
                    <toolbar title="用户中心"></toolbar>
                </appbar>
            </vertical>
        )
    }
    
    /**
     * 
     * @returns 0
     * 加工templace模板
     */
    this.__uiInit__ = function () {
        let appbar = this.templace.getElementById("appbar")
        appbar.attr("bg", this.__uiConfig__.color)
        appbar.appendElement("toolbar").attr("id", "toolbar").attr("title", this.__uiConfig__.title).attr("subtitle", this.__uiConfig__.subTitile)

        if (this.__uiConfig__.tabs.length>0) {
            let xml = ""
            let toolbar = this.templace.getElementById("toolbar")
            let __main__ = this.templace.getElementById("__main__")
            
            __main__.appendElement("viewpager").attr("w", "*")
            .attr("h", "*").attr("id", "viewpager");
            appbar.appendElement("tabs").attr("id", "tabs")

            let viewpager = this.templace.getElementById("viewpager")
            
            for (let i = 0;i<this.__uiConfig__.tabs.length; i++) {
                viewpager.appendElement("scroll").appendElement("vertical").attr("id", this.__uiConfig__.tabs[i]).text("")
            }
            delete xml
            delete toolbar
            delete viewpager
            delete __main__
        } else {
            let __main__ = this.templace.getElementById("__main__")
            __main__.appendElement("frame").attr("w", "*").attr("h", "*").attr("id", "main").text("")
            delete __main__
        }
        delete appbar
        this.templace = this.templace.getElementById("__main__")
        return 0
    }

    this.__uiLoad__ = function (fun) {
        ui.emitter.on("create_options_menu", menu => {
            menu.add("关于")
            menu.add("日志")  
        })
        
        ui.emitter.on("options_item_selected", (e, item) => {
            switch (item.getTitle()) {
                case "关于":
                    dialib.customize()
                    
                    break;
                case "日志":
                    break;
            }
            e.consumed = true
        })
        
        activity.setSupportActionBar(ui.toolbar)
        if (this.__uiConfig__.tabs.length > 0) {
            ui.viewpager.setTitles(this.__uiConfig__.tabs)
            ui.tabs.setupWithViewPager(ui.viewpager)
            // 设置tabs颜色
            ui.tabs.setSelectedTabIndicatorColor(colors.parseColor(this.__uiConfig__.tabs_color))
        }

        // 设置状态栏颜色
        ui.statusBarColor(this.__uiConfig__.color);
        
        // 添加权限
        if (fun && fun instanceof Function) fun.call(this);
        return 0
    }
    
    this.run = function (fun) {
        ui.layout(this.templace);
        this.b_run = true
        this.__uiLoad__(fun)
        for (let i = 0; i < this.checkfun.length; i++) {
            if (this.checkfun[i] != null && this.checkfun[i] instanceof Function) {
                this.checkfun[i].call(this)
            }
        }
        return 0;
    }

    this.runScript = function (jsstr) {
        

    }

    this.save_view = function () {
        if (this.__ids__.length == 0) return;
        
        this.__ids__.forEach(function(v, i) {
            if (v == null || v == "") return;
            //获取控件类型
            let view = ui[v]

            let className = view.getClass().toString().split(" ")[1]
            let value = null;
            print("className -->> "+className)

            switch (className) {
                case "com.stardust.autojs.core.ui.widget.JsEditText":
                    console.log("ajedit")
                    //取值、写入
                    value = view.getText()
                    console.log(value)
                    this.store.put(v, {
                        type: "edit",
                        value: value
                    })
                break;
                case "android.widget.EditText":
                    console.log("edit")
                    value = view.getText()
                    console.log(value)
                    this.store.put(v, {
                        type: "edit",
                        value: value
                    })
                break;
                case "android.widget.CheckBox":
                    console.log("多选")
                    value = view.isChecked()
                    console.log(value)
                    this.store.put(v, {
                        type: "checked",
                        value: value
                    })
                break;
                case "android.widget.RadioButton":
                    console.log("单选")
                    value = view.isChecked()
                    console.log(value)
                    this.store.put(v, {
                        type: "radio",
                        value: value
                    })
                break;
                case "com.stardust.autojs.core.ui.widget.JsSpinner":
                    console.log("下拉菜单")
                    value = view.getSelectedItemPosition()
                    console.log(value)
                    this.store.put(v, {
                        type: "spinner",
                        value: value
                    })
                break;
                case "android.widget.SeekBar":
                    console.log("拖动条")
                    value = view.getProgress()
                    console.log(value)
                    this.store.put(v, {
                        type: "seekbar",
                        value: value
                    })
                break;
                case "android.widget.Switch":
                    console.log("开关")
                    value = view.isChecked()
                    console.log(value)
                    this.store.put(v, {
                        type: "switch",
                        value: value
                    })
                    break;
                default:
                    console.log(className)
                    console.log("不明类型")
            }
        }.bind(this))
    }

    //读取本地view数据写入ui
    this.completion_view = function () {
        
        if (this.__ids__ == null) return;
        if (this.__ids__.length == 0) return;
        this.__ids__.forEach(function(v, i) {
            //读取本地数据
            console.log("读取"+v+"的本地数据")
            let view_data = this.store.get(v)
            if (view_data == null || view_data == "") return;
            if (ui[v] == null) return;
            console.log("开始载入UI配置")
            
            switch(view_data.type){
                case "edit":
                    ui[v].setText(view_data.value)
                    //添加焦点
                    // ui[v].on("touch_down", function() {
                    //     ui.requestFocus()
                    //     ui[v].requestFocus()
                        
                        
                    // }.bind(this))
                break;
                case "checkbox":
                    ui[v].setChecked(view_data.value)
                break;
                case "radio":
                    ui[v].setChecked(view_data.value)
                break;
                case "spinner":
                    ui[v].setSelection(view_data.value)
                break;
                case "seekbar":
                    ui[v].setProgress(view_data.value)
                break;
                case "switch":
                    ui[v].setChecked(view_data.value)
                break;
            }
            
        }.bind(this))
    }

    this.runScriptFile = function (js_path) {
        // 权限坚定

        // 用户坚权
        // 保存配置
        print(this.__ids__)
        print(this.save_view())

        
        
        engines.execScriptFile(js_path, {
            path: this.g_workpath
        })

    }
    
    this.addJsonView = function (js, tab, fun) {
        let xml = this.__json2xml__(js)
        this.addView(xml, tab, fun)
        return 0
    }

    this.__array2xml = function (obj) {
        print("-----")
        let xml = ""
        for (now_tag in obj) {
            print(now_tag)

            let now_view = obj[now_tag]
            xml +=  "<"+now_tag
            let xml_content = ""
            for (p in now_view) {
                let now_p = now_view[p]
                if (!now_p) continue;

                if (p != "child") {
                    xml += " " + p+"="+"\""+now_p+"\""
                }
            }


            
            xml+= ">"
            if (now_view["child"] != null) {
                
                xml_content = this.__array2xml(now_view["child"])
                print("--xml_content--")
                
                print(xml_content)
                xml += xml_content

            }

            
            xml += "<\/"+now_tag+">"

        }
        print(xml)

        return xml
    }

    this.__json2xml__ = function (js) {
        let temp = <card cardCornerRadius="15dp" cardElevation="3dp" w="*" h="auto" margin="6dp">
            <vertical>
                <text text={js.title} w="*" bg="#b2b2b2" gravity="center" padding="4dp" textSize="18sp" textStyle="bold" textColor="#000000"></text>
                <vertical padding="2dp">
                    {this.__array2xml(js.views)}
                </vertical>
            </vertical>
        </card>

        return temp
    }

    this.setFloaty = function () {
        
    }
    
    this.setDebug = function (r) {
        if (!r) return;
        if (r.constructor === Boolean) this.__debug__ = r;
    }
    
    this._log = function () {
        if (this.__debug__) {
            jscode = "print("
            // print(arguments.length)
            for (let i = 0;i < arguments.length; i++) {
                jscode += "\"" + arguments[i] + "\""
                if (i < arguments.length-1) jscode += ", ";
            }
            jscode += ")"
            eval(jscode)
        }
        return null
    }
    
    this._toast = function (str) {
        if (this.__debug__) toastLog(str);
        delete str
        return null
    }   
}